package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author YYP
 * @date 2020/11/13
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SubjectUserContext subjectUserContext;
    /**
     * 用户注册
     * @param userVo
     * @return
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        //对象传换vo-》pojo
        //BeanConv我们自己封装的工具，底层依赖的是我们之前解除的BeanUtils工具
        User user = BeanConv.toBean(userVo, User.class);
        //对密码加密
        user.setPassword(MD5Coder.md5Encode(userVo.getPassword()));
        System.out.println("service：转完后的对象"+user);
        //调用dao完成注册
        int i = userMapper.insert(user);
        return i>0;
    }

    /**
     * 用户登陆
     * @param userVo
     * @return
     */
    @Override
    public UserVo loginUser(UserVo userVo) {
        //拼接查询条件
        UserExample example = new UserExample();
        example.createCriteria()
                .andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));

        List<User> userList = userMapper.selectByExample(example);
        if (userList.size() > 0) {
            //pojo:与数据库表以一对应的
            User user = userList.get(0);
            //vo:与web层的业务一一对应
            UserVo resultUserVo = BeanConv.toBean(user, UserVo.class);
            //---------------------
            //登陆成功后将登陆成功的用户信息保存到session中
            //此对象为session封装数据时使用到的对象
            //session中用于存放数据的对象
            SubjectUser subjectUser = BeanConv.toBean(resultUserVo, SubjectUser.class);
            //生成存放到session中对象的key
            String accessToken = UUID.randomUUID().toString();
            //将token存放到响应结果对象中，（为的是下一次请求时携带token，这样才能从session中获取对应的数据信息）
            resultUserVo.setToken(accessToken);
            subjectUser.setToken(accessToken);
            //将登录成功的信息保存到session中
            subjectUserContext.createdSubject(accessToken,subjectUser);
            //-----------------------
            return resultUserVo;
        }
        return null;
    }


    /**
     * 退出
     */
    @Override
    public void loginOutUser() {
        subjectUserContext.deleteSubject();

    }

    /**
     * 判断用户是否登录
     * @return
     */
    @Override
    public Boolean isLogin() {
        return subjectUserContext.existSubject();
    }
}
